import { ref, computed, watch } from 'vue'
import { validateSql } from '../utils/sqlValidator'

/**
 * SQL验证组合式函数
 * @param {Object} options - 配置选项
 * @returns {Object} 验证相关的响应式数据和方法
 */
export default function useSqlValidation(options = {}) {
  const {
    content = ref(''),
    autoValidate = true,
    debounceTime = 300
  } = options

  // 响应式状态
  const validationResult = ref({
    isValid: true,
    errors: [],
    warnings: []
  })
  
  // 计算属性
  const isValid = computed(() => validationResult.value.isValid)
  const hasErrors = computed(() => validationResult.value.errors.length > 0)
  const hasWarnings = computed(() => validationResult.value.warnings.length > 0)
  const errorCount = computed(() => validationResult.value.errors.length)
  const warningCount = computed(() => validationResult.value.warnings.length)
  
  // 防抖定时器
  let debounceTimer = null

  // 防抖验证
  const debouncedValidate = () => {
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
    
    debounceTimer = setTimeout(() => {
      validate()
    }, debounceTime)
  }

  // 验证SQL
  const validate = () => {
    validationResult.value = validateSql(content.value)
    return validationResult.value
  }

  // 清除验证结果
  const clearValidation = () => {
    validationResult.value = {
      isValid: true,
      errors: [],
      warnings: []
    }
  }

  // 监听内容变化
  if (autoValidate) {
    watch(content, () => {
      debouncedValidate()
    })
  }

  // 清理函数
  const cleanup = () => {
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
  }

  return {
    validationResult,
    isValid,
    hasErrors,
    hasWarnings,
    errorCount,
    warningCount,
    validate,
    debouncedValidate,
    clearValidation,
    cleanup
  }
} 